<?php

namespace app\admin\controller\qingdong\dingding;

use addons\qingdong\library\Ding;
use app\common\controller\Backend;
use addons\qingdong\model\StaffDepartment;
use addons\qingdong\model\DingStaff;
use addons\qingdong\model\DingCustomer;
use addons\qingdong\model\DingContacts;
use addons\qingdong\model\DingRecord;

/**
 * 钉钉同步
 *
 */
class Dingding extends Backend
{
    public function __construct(){
        date_default_timezone_set('Asia/Shanghai');
        $ding=new Ding();
        //获取access_token
        $token = $ding->getAccessToken();
        if($token->errcode != 0){
            $this->error($token->errmsg);
        }
        $this->access_token = $token->access_token;
    }

    /**
     * 获取部门
     */
    public function index(){
       $ding=new Ding();
        $accessToken = $this->access_token;
        //获取部门
        $department = $ding->departmentInfo($accessToken);
        if($department->errcode != 0){
            $this->error($department->errmsg);
        }
        foreach($department->result as $k=>$v){
            $departmentData = StaffDepartment::where(array('id'=>$v->dept_id))->find();
            if($departmentData){
                continue;
            }
            $deRes = array(
                'id'=>$v->dept_id,
                'name'=>$v->name,
            );
            $departmentInfo = StaffDepartment::create($deRes);
            //查找他的下级部门
            if($departmentInfo){
                $dept_id = $v->dept_id;
                $this->deepDep($accessToken,$dept_id);
            }
        }
        $this->success('同步成功');
    }
    //递归获取子部门
    public function deepDep($accessToken,$depid=0,&$arr=[]){
        $ding=new Ding();

        //获取部门
        $department = $ding->departmentInfo($accessToken,$depid);
        if($department->errcode != 0){
            $this->error($department->errmsg);
        }
        if(count($department->result)>0){
            foreach($department->result as $k=>$v){
                $arr[] = $v;
                $deRes1 = array(
                    'id'=>$v->dept_id,
                    'pid'=>$v->parent_id,
                    'name'=>$v->name,
                );
                StaffDepartment::create($deRes1);
                $this->deepDep($accessToken,$v->dept_id,$arr);
            }

        }
        return $arr;
    }
    /**
     * 获取员工
     */
    public function staffinfo(){
        $ding=new Ding();
        $accessToken = $this->access_token;
        $department = StaffDepartment::where(array('type'=>0))->select();
        if(!$department){
            $this->error('部门为空,请先同步部门');
        }
        foreach($department as $k=>$v){
            $staff =$ding->staffInfo($accessToken,$v['id']);
            if($staff->errcode != 0 || !$staff->result->list){
                continue;
            }

            foreach($staff->result->list as $ks=>$vs){
                //重复员工记录不存储
                $staffFind = DingStaff::where(array('user_id' =>$vs->userid,'type'=>0))->find();
                if($staffFind){
                    continue;
                }
                $resmobile = $ding->staffInfoDetail($accessToken,$vs->userid);
                $mobile = '';
                if($resmobile->errcode == 0){
                    if(property_exists($resmobile->result,'mobile')){
                        $mobile =$resmobile->result->mobile;
                    }

                }

                $staffUser = array(
                    'dept_id' =>$v['id'],
                    'user_id' =>$vs->userid,
                    'name' =>filter_Emoji($vs->name),
                    'mobile' => $mobile,
                    'status' =>0,
                );
                DingStaff::create($staffUser);
            }
        }
        $this->success('同步成功');
    }
    /**
     * 批量获取客户
     */
    public function customer(){
        $ding=new Ding();
        $accessToken = $this->access_token;
        $DingStaff = DingStaff::where(array('type'=>0))->select();
        if(!$DingStaff){
            $this->error('员工为空,请先同步员工为空');
        }

        foreach($DingStaff as $k=>$v){
            $customer = $ding->customerBatch($accessToken,$v['user_id']);

            if($customer->errcode != 0 || !$customer->result->values){
                continue;
            }
            foreach($customer->result->values as $ks=>$vs){
                $customerFind = DingCustomer::where(array('instance_id'=>$vs->instance_id,'type'=>0))->find();
                if($customerFind){
                    continue;
                }
                $data = json_decode($vs->data,true);
                $instance_id = $vs->instance_id;
                $customers = isset($data['customer_name']) ? $data['customer_name'] : '';
                $adressinfo = isset($data['address']['extendValue']) ? json_decode($data['address']['extendValue'],true) : '';
                $address_detail = '';
                $address = '';
                if($adressinfo){
                    $province = isset($adressinfo['province']['name']) ? $adressinfo['province']['name'] : '';
                    $city  = isset($adressinfo['city']['name']) ? $adressinfo['city']['name'] : '';
                    $district  = isset($adressinfo['district']['name']) ? $adressinfo['district']['name'] : '';
                    $address_detail  = isset($adressinfo['detail']['name']) ? $adressinfo['detail']['name'] : '';
                    $address = $province.$city.$district;
                }
                $remark = isset($data['TextareaField-K55CWZ2E']) ? $data['TextareaField-K55CWZ2E'] : '';
                $source = isset($data['DDSelectField-K2U5GX3B']['value']) ? $data['DDSelectField-K2U5GX3B']['value'] : '';
                $owner_staff_id=$vs->permission->owner_userid_list[0];
                $create_staff_id=$vs->creator_userid;
                $createtime = strtotime($vs->gmt_create);
                $updatetime = strtotime($vs->gmt_modified);
                $customerData = array(
                    'instance_id'=>$instance_id,
                    'user_id'=>$create_staff_id,
                    'name'=>$customers,
                    'address'=>$address,
                    'address_detail'=>$address_detail,
                    'source'=>$source,
                    'remark'=>$remark,
                    'owner_staff_id'=>$owner_staff_id,
                    'create_staff_id'=>$create_staff_id,
                    'createtime'=>$createtime,
                    'updatetime'=>$updatetime,
                );
                DingCustomer::create($customerData);
            }
        }
        $this->success('同步成功');

    }
    /**
     * 批量获取联系人
     */
    public function contacts(){
        $ding=new Ding();
        $accessToken = $this->access_token;
        $DingStaff = DingStaff::where(array('type'=>0))->select();
        if(!$DingStaff){
            $this->error('员工为空,请先同步员工为空');
        }
        foreach($DingStaff as $k=>$v){
            $customer = $ding->contactsBatch($accessToken,$v['user_id']);
            if($customer->errcode != 0 || !$customer->result->values){
                continue;
            }
            foreach($customer->result->values as $ks=>$vs){
                $customerFind = DingContacts::where(array('instance_id'=>$vs->instance_id))->find();
                if($customerFind){
                    continue;
                }
                $data = json_decode($vs->data,true);
                $contact_related_customer = json_decode($data['contact_related_customer']['extendValue'],true);
                $instanceId = isset($contact_related_customer['list'][0]['instanceId']) ? $contact_related_customer['list'][0]['instanceId'] : '';
                if(!$instanceId){
                    continue;
                }
                $customerId = DingCustomer::where(array('instance_id'=>$instanceId))->value('id');
                if(!$customerId){
                    continue;
                }
                $instance_id = $vs->instance_id;
                $contact_name = isset($data['contact_name']) ? $data['contact_name'] : '';
                $post = isset($data['contact_position']['extendValue']) ? json_decode($data['contact_position']['extendValue'],true)[0]['label'] : '';
                $email = isset($data['TextField-K55DPXC9']) ? $data['TextField-K55DPXC9'] : '';
                $mobile = isset($data['contact_phone']['value']) ? $data['contact_phone']['value'] : '';
                $remark = isset($data['TextareaField-K2UG1B59']) ? $data['TextareaField-K2UG1B59'] : '';
                $owner_staff_id=$vs->permission->owner_userid_list[0];
                $create_staff_id=$vs->creator_userid;
                $createtime = strtotime($vs->gmt_create);
                $updatetime = strtotime($vs->gmt_modified);
                $customerData = array(
                    'instance_id'=>$instance_id,
                    'customer_id'=>$customerId,
                    'name'=>$contact_name,
                    'post'=>$post,
                    'email'=>$email,
                    'mobile'=>$mobile,
                    'remarks'=>$remark,
                    'owner_staff_id'=>$owner_staff_id,
                    'create_staff_id'=>$create_staff_id,
                    'createtime'=>$createtime,
                    'updatetime'=>$updatetime,
                );
                DingContacts::create($customerData);
            }
        }
        $this->success('同步成功');
    }
    /**
     * 批量获取跟进记录
     */
    public function record(){
        $ding=new Ding();
        $accessToken = $this->access_token;

        $DingStaff = DingStaff::select();
        if(!$DingStaff){
            $this->error('员工为空,请先同步员工为空');
        }
        foreach($DingStaff as $k=>$v){
            $customer = $ding->recordBatch($accessToken,$v['user_id']);
            if($customer->errcode != 0 || !$customer->result->values){
                continue;
            }
            foreach($customer->result->values as $ks=>$vs){
                $customerFind = DingRecord::where(array('instance_id'=>$vs->instance_id))->find();
                if($customerFind){
                    continue;
                }
                $data = json_decode($vs->data,true);
                $contact_related_customer = json_decode($data['follow_record_related_customer']['extendValue'],true);
                $instanceId = isset($contact_related_customer['list'][0]['instanceId']) ? $contact_related_customer['list'][0]['instanceId'] : '';
                if(!$instanceId){
                    continue;
                }
                $customerId = DingCustomer::where(array('instance_id'=>$instanceId))->value('id');
                if(!$customerId){
                    continue;
                }
                $instance_id = $vs->instance_id;
                $content = isset($data['TextareaField-K2U5UJAF']) ? $data['TextareaField-K2U5UJAF'] : '';
                $create_staff_id=$vs->creator_userid;
                $createtime = strtotime($vs->gmt_create);
                $updatetime = strtotime($vs->gmt_modified);
                $customerData = array(
                    'instance_id'=>$instance_id,
                    'customer_id'=>$customerId,
                    'content'=>$content,
                    'create_staff_id'=>$create_staff_id,
                    'createtime'=>$createtime,
                    'updatetime'=>$updatetime,
                );
                DingRecord::create($customerData);
            }
        }
        $this->success('同步成功');
    }
}